//
//  ViewController.m
//  图片上传
//
//  Created by 我演示 on 2019/11/13.
//  Copyright © 2019 ALLSall. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

   //上传图片相关的方法
    -(void)btnClick {
        //此处image是在项目中自取的image,读者注意自己拿到图片的方式,测试的话可以在项目中加入一张11.png的图片
        UIImage *image = [UIImage imageNamed:@"11.png"];
        //下面是iOS两种获取图片的方法，一种获取为jpeg，一种获取为png
        //转为jpeg上传可以让图片的大小压缩
        NSMutableArray *photos = [NSMutableArray array];
        [photos addObject:image];
        //temp为服务器URL;
        NSString *url = @"------------------";
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            //参数name：是后台给你的图片在服务器上字段名;
            //参数fileNmae：自己起得一个名字，
            //参数mimeType：这个是决定于后来接收什么类型的图片，接收的时png就用image/png ,接收的时jpeg就用image/jpeg
            for (int i = 0; i < photos.count; i++) {
                NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
                formatter.dateFormat=@"yyyyMMddHHmmss";
                NSString *str=[formatter stringFromDate:[NSDate date]];
                NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
                UIImage *image = photos[i];
                NSData *imageData = UIImageJPEGRepresentation(image, 0.28);
                [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"upload%d",i+1] fileName:fileName mimeType:@"image/jpeg"];
                
            }
            // [formData appendPartWithFileData:imageData name:@"Filedata" fileName:@"Filedate.png" mimeType:@"image/png"];
            
        } error:nil];
        
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        //设置服务器返回内容的接受格式
        AFHTTPResponseSerializer *responseSer = [AFHTTPResponseSerializer serializer]; responseSer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
        manager.responseSerializer = responseSer;
        // NSProgress *progress = nil;
        NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if (error) { NSLog(@"Error: %@", error);
                
            } else {
                NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSLog(@"%@\n %@", response, str);
                
            }
            
        }];
        [uploadTask resume];
        
    }

@end





// 1.请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    NSString *url = [NSString stringWithFormat:@"%@/App/Index/userphoto/",SERVERURL];
    // 2.拼接请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"mobile"] = self.userMobileLbl.text;
    // 3.发送请求
    [mgr POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // 拼接文件数据
        NSData *data = UIImageJPEGRepresentation(localImg, 1.0);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
         // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        [formData appendPartWithFileData:data name:@"img1" fileName:fileName mimeType:@"image/jpg"];
    } success:^(AFHTTPRequestOperation *operation, NSDictionary *json) {
//        LXLog(@"%@", json);
        [MBProgressHUD hideHUD];
        [json[@"status"] isEqual: @"1"] ? [MBProgressHUD showSuccess:@"上传成功!"]:[MBProgressHUD showError:@"上传失败!"];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD showError:@"上传头像失败，请重新上传"];
    }];







AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
  
//2.上传文件
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"userHeader.png", @"userHeader", @"image.png", @"image", nil nil];
[manager POST:URL parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
  
    //上传文件参数
    [formData appendPartWithFileData:data1 name:@"userHeader" fileName:@"userHeader.png" mimeType:@"image/jpeg"];
    [formData appendPartWithFileData:data2 name:@"image" fileName:@"image.png" mimeType:@"image/jpeg"];
      
} progress:^(NSProgress * _Nonnull uploadProgress) {
      
    //打印上传进度
    CGFloat progress = 100.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
    DLog(@"%.2lf%%", progress);
      
} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
      
    //请求成功
    DLog(@"请求成功：%@",responseObject);
      
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
      
    //请求失败
    DLog(@"请求失败：%@",error);
  
}];
